package response

import (
	"longmen/server/internal/services/nami/config"
	lol2 "longmen/server/internal/services/nami/services/esport/lol"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

type StatusID int
type MatchResponse struct {
	Code    int `json:"code"`
	Results []struct {
		ID         int `json:"id"`
		Box        int `json:"box"`
		Tournament struct {
			ID int `json:"id"`
		} `json:"tournament"`
		Stage struct {
			ID int `json:"id"`
		} `json:"stage"`
		Home struct {
			ID    int    `json:"id"`
			Score uint32 `json:"score"`
		} `json:"home"`
		Away struct {
			ID    int    `json:"id"`
			Score uint32 `json:"score"`
		} `json:"away"`
		MatchTime int64    `json:"match_time"`
		StatusID  StatusID `json:"status_id"`
		Coverage  struct {
			Mlive int `json:"mlive"`
		} `json:"coverage"`
		Description string `json:"description"`
		UpdatedAt   int    `json:"updated_at"`
	} `json:"results"`
}

func (s StatusID) String() string {
	//0	比赛异常，说明：暂未判断具体原因的异常比赛，建议隐藏处理
	status := map[int]string{
		1:  "未开赛",
		2:  "进行中",
		3:  "完场",
		11: "中断",
		12: "取消",
		13: "延期",
		14: "腰斩",
		15: "待定",
	}
	str, ok := status[int(s)]
	if !ok {
		return ""
	}
	return str
}

func (s StatusID) MatchStatus() uint32 {
	// 比赛状态, 1-进行,2-未开赛,3-完场
	if s == 1 {
		return 2 // 2-未开赛
	}
	if s == 3 {
		return 3 // 3-完场
	}
	if s == 2 {
		return 1 // 1-进行
	}
	if s == 0 || s >= 11 && s <= 15 {
		return 4 // 4-异常
	}
	return 0
}

func (m MatchResponse) MatchTemp() []*models_sports.MatchTempSchedule {
	records := make([]*models_sports.MatchTempSchedule, 0)
	matchId := make([]int, 0)
	teamIds := make([]int, 0)
	tournamentIds := make([]int, 0)
	for _, result := range m.Results {
		matchId = append(matchId, result.ID)
		teamIds = append(teamIds, result.Home.ID)
		teamIds = append(teamIds, result.Away.ID)
		tournamentIds = append(tournamentIds, result.Tournament.ID)
	}
	if len(matchId) == 0 {
		return records
	}

	tournamentMaps, _ := lol2.GeTournamentIdMaps(tournamentIds)
	teamMaps, _ := lol2.GetTeamIdMaps(teamIds)

	for _, result := range m.Results {
		tournament, ok := tournamentMaps[result.Tournament.ID]
		if !ok {
			continue
		}

		home, ok := teamMaps[result.Home.ID]
		if !ok {
			continue
		}
		away, ok := teamMaps[result.Away.ID]
		if !ok {
			continue
		}

		records = append(records, &models_sports.MatchTempSchedule{
			MatchId:           result.ID,
			MatchTime:         result.MatchTime,
			SportId:           config.LOL,
			Comp:              tournament.NameZh,
			CompShortZh:       tournament.AbbrZh,
			CompLogo:          tournament.Logo,
			Home:              home.NameZh,
			HomeLogo:          home.Logo,
			Away:              away.NameZh,
			AwayLogo:          away.Logo,
			HomeScore:         result.Home.Score,
			AwayScore:         result.Away.Score,
			TimePlayed:        0,
			MatchStatus:       result.StatusID.MatchStatus(),
			MatchDetailStatus: result.StatusID.String(),
			RawMatchStatus:    uint32(result.StatusID),
		})
	}

	return records
}
